package com.gzxx.security;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author MAX
 * @date 2020/7/24 10:49 上午
 */

@Component("rbac")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class RbacPermissionService {

    private final TokenService tokenService;

    public boolean hasPermission(String permission) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (StringUtils.isEmpty(permission)) {
            return false;
        }

        CurrentUser loginUser = tokenService.getLoginUser(request);
        boolean privileged = !ObjectUtils.isEmpty(loginUser) && loginUser.getPermissions().contains(permission);
        //检测token是否快过期
        if(privileged) {
            tokenService.refreshToken(request);
        }

        return privileged;
    }
}
